package com.example.feature.demo.service;

import com.example.feature.demo.util.snowflake.IDGen;
import com.example.feature.demo.util.snowflake.InitException;
import com.example.feature.demo.util.snowflake.Result;
import com.example.feature.demo.util.snowflake.SnowflakeIDGenImpl;
import com.example.feature.demo.util.snowflake.Status;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

@Service("SnowflakeService")
public class SnowflakeService implements ApplicationListener<WebServerInitializedEvent> {
    private Logger logger = LoggerFactory.getLogger(SnowflakeService.class);

    private IDGen idGen;

    private int serverPort;

    @Value("${leaf.snowflake.zk.address}")
    private String zkAddress;

    @Value("${leaf.name}")
    private String leafName;

    public long getId() {
        Result result;
        do {
            result = idGen.get();
        } while (!Status.SUCCESS.equals(result.getStatus()));
        return result.getId();
    }

    public Result get() {
        return idGen.get();
    }

    @SneakyThrows
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
        idGen = new SnowflakeIDGenImpl(zkAddress, serverPort, leafName);
        if (idGen.init()) {
            logger.info("Snowflake Service Init Successfully");
        } else {
            throw new InitException("Snowflake Service Init Fail");
        }
    }


}
